package com.yj.controller;

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.yj.entity.ChatContent;
import com.yj.entity.ReturnT;
import com.yj.service.MessageHandlerProcess;
import com.yj.util.AbstractProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
public class QytwController {

    @Autowired
    private List<MessageHandlerProcess> messageHandlerProcessList;

    @PostMapping("chat")
    public ReturnT chat(@RequestBody ChatContent chatContent) {

        return new AbstractProcessService<ChatContent, ReturnT>() {
            @Override
            public void volidateParams(ChatContent content) throws Exception {
                if (Objects.isNull(content)) {
                    throw new Exception("content is required");
                }
                if (Objects.isNull(content.getMessage())) {
                    throw new Exception("message is required");
                }
            }

            @Override
            public ReturnT doProcess(ChatContent content) {

                for (MessageHandlerProcess messageHandlerProcess : messageHandlerProcessList) {
                    if (messageHandlerProcess.support(content)) {
                        return ReturnT.success(messageHandlerProcess.process(content));
                    }
                }
                return ReturnT.success("暂不支持该功能");
            }
        }.doProcess(chatContent);

    }


    public static void callAgentApp()
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                .apiKey("YOUR_API_KEY")
                .appId("39349a8818584be2905b911107f344ff")
                .prompt("如何做炒西红柿鸡蛋？")
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        System.out.printf("requestId: %s, text: %s, finishReason: %s\n",
                result.getRequestId(), result.getOutput().getText(), result.getOutput().getFinishReason());
    }

    public static void main(String[] args) {
        try {
            callAgentApp();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
        }
        System.exit(0);
    }
}
